import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';

class ApiResponse<T> {
  constructor(
    public success: boolean,
    public code: number,
    public message: string,
    public data: T,
    public timestamp: string,
    public path: string,
  ) {}
}

@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status =
      exception instanceof HttpException ? exception.getStatus() : 500;

    const res =
      exception instanceof HttpException ? exception.getResponse() : null;
    const message =
      typeof res === 'string'
        ? res
        : Array.isArray(res?.['message'])
          ? res['message'][0]
          : res?.['message'] || 'Internal server error';

    response
      .status(status)
      .json(
        new ApiResponse(
          false,
          status,
          message,
          null,
          new Date().toISOString(),
          request?.url,
        ),
      );
  }
}
